package com.etoak.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.redis.RedisService;
import com.etoak.dto.LoginDTO;
import com.etoak.entity.User;
import com.etoak.jwt.JwtUtil;
import com.etoak.mapper.UserMapper;
import com.etoak.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.AccessToken;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * UserServiceImpl
 *
 * @author etoak
 * @since 2024-12-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RedisService redisService;

    @Override
    public AccessToken login(LoginDTO loginDTO) {
        String savedCode = redisService.get(CommonConstant.REDIS_CODE_PREFIX + loginDTO.getUuid());
        if (!StringUtils.equalsIgnoreCase(savedCode, loginDTO.getCode())) {
            throw new CustomException("验证码错误或已过期!");
        }

        String password = MD5.create().digestHex(loginDTO.getPassword());
        User user = lambdaQuery().eq(User::getUsername, loginDTO.getUsername())
                .eq(User::getPassword, password)
                .one();

        if (ObjectUtils.isEmpty(user)) {
            throw new CustomException("用户名或密码错误!");
        }

        // JWT(JSON Web Token) Header.Payload.Signature
        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put("id", String.valueOf(user.getId()));
        claimsMap.put("username", user.getUsername());

        String accessToken = JwtUtil.create(claimsMap);

        return new AccessToken(user.getUsername(), accessToken);
    }
}
